<template>
    <div class="calculator-pge">
        <x-header :left-options="{backText: ''}">贷款计算器</x-header>
        <div class="calculator-blank">
            <img src="../../assets/img/calcBg.jpg">
        </div>
        <div class="calculator-error">
            <p v-text="errorText" class="error-text"
               :class="{'calculator-entererror-text':isActive,'calculator-gouterror-text':!isActive}"></p>
        </div>
        <group class="calculator-input" label-width="100px">
            <x-input title="贷款金额"
                     v-model.trim="loanVal"
                     :novalidate="true"
                     :max="7"
                     type="tel"
                     placeholder="请输入金额"
                     @on-focus="hideerr"
                     @input.native="handleInputLoanVal"
                     text-align="right"
                     is-link>
                <span slot="right" class="unit">元</span>
            </x-input>
            <cell title="贷款期数"
                  :value="monthVal.label"
                  is-link
                  :class="{'cell-select': monthVal.label !== '请选择'}"
                  @click.native="showsheet"></cell>
            <x-input title="月利率"
                     v-model.trim="monthRate"
                     placeholder="请输入月利率"
                     @input.native="handleInputMonthRate"
                     @on-focus="hideerr"
                     text-align="right"
                     placeholder-align="right">
                <span slot="right" class="unit">%</span>
            </x-input>
            <cell title="还款方式"
                  :value="repaymentVal.selecteLabel"
                  is-link
                  :class="{'cell-select': repaymentVal.selecteLabel !== '请选择'}"
                  @click.native="showRepayments"></cell>
            <actionsheet v-model="show" :menus="mouths" @on-click-menu="getSelectedMonth" show-cancel></actionsheet>
            <actionsheet v-model="show1" :menus="repayments" @on-click-menu="getSelectedRepayments"
                         show-cancel></actionsheet>
        </group>
        <FButton @on-click-button="gotoPage">开始计算</FButton>
        <!--模态窗-->
        <div v-show="calulatorResult" class="calulator-result-modal">
            <div class="calculateresult-page">
                <div class="returnInfo">
                    <x-header @on-click-back="backPage" :left-options="{backText: '',preventGoBack:true}">贷款计算器
                    </x-header>
                    <div class="calculatorresult-blank">
                        <p>共需还款</p>
                        <p>¥{{sumRepayment | formatNum}}</p>
                    </div>
                    <flexbox class="calculatorresult-center">
                        <flexbox-item>
                            <p>
                                <span>贷款金额</span> <br>
                                <span>¥ {{loanVal | formatNum}}</span>
                            </p>
                        </flexbox-item>
                        <flexbox-item>
                            <p>
                                <span>贷款利息</span> <br>
                                <span>¥ {{sumAccrual | formatNum}} </span>
                            </p>
                        </flexbox-item>
                        <flexbox-item>
                            <p>
                                <span>贷款期数</span> <br>
                                <span>{{ monthVal.val }}个月</span>
                            </p>
                        </flexbox-item>
                    </flexbox>
                    <div class="calculatorresult-body">
                        <span>期数</span>
                        <span>月供(元)</span>
                        <span>本金(元)</span>
                        <span>利息(元)</span>
                    </div>
                </div>
                <div class="repPlantLists" :style="{ height: resultHeight }">
                    <div class="calculatorresult-detail" v-for="i in lists">
                        <span>第{{i.periods}}期</span>
                        <span>{{i.payment | formatNum}}</span>
                        <span>{{i.principal | formatNum}}</span>
                        <span>{{i.accrual | formatNum}}</span>
                    </div>
                </div>
            </div>
        </div>
        <!--模态窗的结束-->
    </div>
</template>
<script>
    /**
     * Created by z.x.q on 2018/3/22.
     * 计算器的首页
     */
    import {Actionsheet, Cell, Flexbox, FlexboxItem, XButton, Group, XDialog, XHeader, XInput} from 'vux';
    import FButton from '../../components/common/FButton';
    import validator from '../../tool/validator';

    export default {
        name: 'f-calculator',
        components: {
            XHeader,
            Group,
            XInput,
            Cell,
            Actionsheet,
            FButton,
            XButton,
            XDialog,
            Flexbox,
            FlexboxItem
        },
        data() {
            return {
                isActive: false,
                resultHeight: 0, // 计算结果页的高度
                show: false,
                show1: false,
                sumAccrual: 0,   // 总利息
                sumRepayment: 0,  // 总还款数
                errorText: '',
                calulatorResult: false,  // 展示显示结果
                loanVal: null,
                monthRate: null,
                repaymentVal: {
                    selecteLabel: '请选择',
                    type: null
                },
                monthVal: {
                    label: '请选择',
                    val: null
                },
                mouths: [
                    {label: '60个月', val: 60},
                    {label: '36个月', val: 36},
                    {label: '24个月', val: 24},
                    {label: '18个月', val: 18},
                    {label: '12个月', val: 12},
                    {label: '9个月', val: 9},
                    {label: '6个月', val: 6},
                    {label: '3个月', val: 3},
                    {label: '1个月', val: 1},
                ],
                repayments: [{
                    label: '等本等息<br/><span style="color:#666;font-size:12px;">月供，本金，利息每月相同</span>',
                    selecteLabel: '等本等息',
                    type: 3
                }, {
                    label: '等额本息<br/><span style="color:#666;font-size:12px;">月供每月相同，本金逐月递增，利息逐月递减</span>',
                    selecteLabel: '等额本息',
                    type: 2
                }, {
                    label: '等额本金<br/><span style="color:#666;font-size:12px;">月供逐月递减，本金每月相同，利息逐月递减</span>',
                    selecteLabel: '等额本金',
                    type: 1
                }, {
                    label: '先息后本<br/><span style="color:#666;font-size:12px;">每月还固定利息，到期还全部本金</span>',
                    selecteLabel: '先息后本',
                    type: 4
                }
                ],
//              模态窗数据
                lists: []
            };
        },
        methods: {
            // 只能输入数字，即正整数，键盘控制的可以只输入数字，但是
            // 用户如果使用的第三方键盘，还是可以输入其他字符
            handleInputLoanVal() {
                let _this = this;
                setTimeout(function () {
                    if (_this.loanVal) {
                        if (_this.loanVal.length > 9) {
                            _this.loanVal = _this.loanVal.substring(0, 9);
                        } else {
                            _this.loanVal = _this.loanVal.replace(/[^\d]/g, '');
                        }
                    }
                }, 50);
            },
            // 月利率输入判断,只能输入小数点，把用户输入的非数字与点的输入替换成空字符串
            handleInputMonthRate() {
                let _this = this;
                setTimeout(function () {
                    if (_this.monthRate) {
                        if (_this.monthRate.length > 6) {
                            _this.monthRate = _this.monthRate.substring(0, 6);
                        } else {
                            _this.monthRate = _this.monthRate.replace(/[^\d.]/g, '');
                        }
                    }
                }, 50);
            },
            showsheet: function () {
                this.show = true;
            },
            showRepayments: function () {
                this.show1 = true;
            },
            getSelectedMonth: function (menuKey, menuItem) {
                if (menuItem) {
                    this.monthVal = menuItem;
                }
            },
            getSelectedRepayments: function (menuKey, menuItem) {
                if (menuItem) {
                    this.repaymentVal = menuItem;
                }
            },
            gotoPage: function () {
                let _this = this;
                if (this.isActive) {
                    return;
                }
                // 跳转计算
                // 判断四个条件是否都输入
                let _loanVal = this.loanVal;        // 还款总额
                let _monthRate = this.monthRate / 100;       // 还款利率
                let _monthVal = this.monthVal.val;  // 还款期数
                let _repayment = this.repaymentVal.type; // 还款类型
                let checkPositiveInteger = /^[1-9]{1}\d{0,8}$/;
                if (validator.checkValEmpty(_loanVal)) {
                    this.errorText = "请输入贷款金额";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                    // 贷款金额需大于500,输入的内容为正整数，没有小数
                } else if (validator.checkValEmpty(_monthVal)) {
                    this.errorText = "请选择贷款期数";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                } else if (validator.checkValEmpty(this.monthRate)) {
                    this.errorText = "请输入月利率";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                } else if (validator.checkValEmpty(_repayment)) {
                    this.errorText = "请选择还款方式";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                } else if (!checkPositiveInteger.test(_loanVal)) {
                    this.errorText = "请输入正确的贷款金额";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                } else if (_loanVal < 500) {
                    this.errorText = "贷款金额需大于500";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                    // 这里的月利率就是这个，不是处于100的，不要修改
                } else if (!validator.checkIntegerAndDot(this.monthRate)) {
                    this.errorText = "请输入正确的月利率";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                } else if (_monthRate.toFixed(4) > 2) {
                    this.errorText = "月利率需小于200%";
                    this.isActive = true;
                    setTimeout(() => {
                        this.isActive = false;
                    }, 2000);
                    return false;
                }
                this.lists = [];
//              =================== 等额本金 ================begin==============
                if (this.repaymentVal.type == 1) {
                    this.sumRepayment = 0;
                    this.sumAccrual = 0;
                    for (let i = 1; i <= _monthVal; i++) {
                        let _obj = {
                            periods: i,            // 期数
                            principal: _loanVal / _monthVal,     // 本金
                            accrual: _loanVal * (_monthVal + 1 - i) / _monthVal * _monthRate     // 利息
                        };
                        _obj.payment = Number(_obj.principal) + Number(_obj.accrual);
                        this.sumAccrual += _obj.accrual;
                        this.lists.push(_obj);
                    }
                    this.sumRepayment = this.sumAccrual + parseInt(this.loanVal);
                }
//=================== 等额本金 ================end==============

//=================== 等额本息 ================begin==============
                if (this.repaymentVal.type == 2) {
                    this.sumRepayment = 0;
                    this.sumAccrual = 0;
                    let _remainingMoney = _loanVal;
                    for (let i = 1; i <= _monthVal; i++) {
                        let _obj = {
                            periods: i,            // 期数
                            principal: 0,     // 本金
                            accrual: 0,    // 利息
                            payment: 0      // 月供
                        };
                        _obj.payment = _loanVal * _monthRate * Math.pow((1 + _monthRate), _monthVal) / (Math.pow((1 + _monthRate), _monthVal) - 1);  // 月供
                        _obj.accrual = _remainingMoney * _monthRate;   // 利息
                        _obj.principal = _obj.payment - _obj.accrual;   // 本金
                        _remainingMoney = _remainingMoney - _obj.principal;
                        this.sumAccrual += _obj.accrual;
                        console.log(_obj);
                        this.lists.push(_obj);
                    }
                    this.sumRepayment = this.sumAccrual + parseInt(this.loanVal);
                }
                //         =============== 等本等息 ================begin==============
                if (this.repaymentVal.type == 3) {
                    this.sumRepayment = 0;
                    this.sumAccrual = 0;
                    for (let i = 1; i <= _monthVal; i++) {
                        let _obj = {
                            periods: i,            // 期数
                            principal: _loanVal / _monthVal,     // 本金
                            accrual: _loanVal * _monthRate,    // 利息
                            payment: 0 // 月供
                        };
                        _obj.payment = _obj.principal + _obj.accrual;  // 月供
                        this.sumAccrual += _obj.accrual;
                        this.lists.push(_obj);
                    }
                    this.sumRepayment = this.sumAccrual + parseInt(this.loanVal);
                }
//=================== 先息后本 ================begin==============
                if (this.repaymentVal.type == 4) {
                    this.sumRepayment = 0;
                    this.sumAccrual = 0;
                    for (let i = 1; i <= _monthVal; i++) {
                        let _obj = {
                            periods: i,            // 期数
                            principal: 0.00,     // 本金
                            accrual: _loanVal * _monthRate   // 利息
                        };
                        if (i == _monthVal) {
                            _obj.payment = Number(_loanVal) + Number(_obj.accrual);  // 月供
                            if (_loanVal) {
                                _obj.principal = parseInt(_loanVal);
                            } else {
                                _obj.principal = 0.00;
                            }

                        } else {
                            _obj.payment = Number(_obj.accrual);  // 月供
                        }
                        this.sumAccrual += _obj.accrual;
                        this.lists.push(_obj);
                    }
                    this.sumRepayment = this.sumAccrual + parseInt(this.loanVal);
                }
//              =================== 等额本金 ================end==============

                this.calulatorResult = true;
            },
            backPage: function () {
                // 模态窗数据清理
                this.calulatorResult = false;
                this.isActive = false;
                this.loanVal = '';
                this.monthRate = '';
                this.repaymentVal = {
                    selecteLabel: '请选择',
                    type: null
                };
                this.monthVal = {
                    label: '请选择',
                    val: null
                };
            },
            hideerr() {
                this.isActive = false;
            }
        },
        filters: {
            formatNum: function (value) {
                if (!value) return '0.00';
                value = value * 1;
                return value.toFixed(2);
            }
        },
        activated: function () {
            // 获取视窗的高度
            let clientHeight = document.documentElement.clientHeight;
            this.resultHeight = (clientHeight - 272) + 'px';
            this.$store.commit('UPDATE_DIRECTION', {direction: 'in'});
        },
        deactivated: function () {
            this.isActive = false;
            this.loanVal = '';
            this.monthRate = '';
            this.show = false;
            this.show1 = false;
            this.repaymentVal = {
                selecteLabel: '请选择',
                type: null
            };
            this.monthVal = {
                label: '请选择',
                val: null
            };
        }
    };

</script>

<style lang="less">
    @import "../../style/mixin.less";

    .calculator-pge {
        height: 100%;
        .vux-header {
            .color-linear-gradient(@color-primary-light, @color-primary, 90deg);
            .vux-header-title {
                font-size: 20PX;
            }
            .vux-header-left {
                .left-arrow:before {
                    border: solid 1px @color-white;
                    border-width: 2px 0 0 2px;
                }
            }
        }
        [class^="weui-icon-"]:before, [class*=" weui-icon-"]:before {
            margin-bottom: 5px;
        }
        .cell-select {
            .weui-cell__ft {
                color: @color-text-primary;
            }
        }
        .calculator-input {
            .weui-cells, .vux-no-group-title {
                margin-top: 0;
            }
        }
        .weui-actionsheet__cell {
            font-size: @font-size-base;
        }
        .calulator-result-modal {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow-y: scroll;
            background: #fff;
            z-index: 10000;
        }
        background-color: @color-background-default;
        .weui-label, .vux-label, .unit {
            font-size: @font-size-base;
        }
        .unit {
            color: @color-black;
            display: inline-block;
            width: 15px;
            height: 15px;
            line-height: 27PX;
        }
        .weui-cell {
            height: 24PX;
            line-height: 24PX;
        }
        .weui-cell__bd, .weui-cell__ft {
            font-size: @font-size-medium;
        }
        .weui-cells:before, .weui-cells:after {
            display: none;
        }
        .weui-cell__bd {
            margin-right: 2%;
        }
        .weui-cell_access {
            .weui-cell__ft {
                padding-right: 20px;
            }
        }
        input::-webkit-input-placeholder {
            color: #999 !important; /* WebKit browsers */
        }
        .calculator-blank {
            height: 150px;
            img {
                width: 100%;
                height: 100%;
                display: block;
            }
        }
        .calculator-error {
            height: 32px;
            width: 100%;
            position: relative;
            overflow: hidden;
            background-color: @color-background-default;
            transition: all .5s;
            .error-text {
                width: 100%;
                height: 32px;
                transition: all .5s;
                line-height: 32px;
                background-color: #ffa523;
                text-align: center;
                color: @color-white;
                position: absolute;
            }
            .calculator-entererror-text {
                top: 0;
            }
            .calculator-gouterror-text {
                top: -32px;
            }
        }
        .f-button, .weui-btn {
            margin-top: 44px;
            font-size: @font-size-primary;
        }
    }

    /*计算结果弹窗样式*/
    .calculateresult-page {
        .weui-actionsheet__cell {
            font-size: 16PX;
        }
        .returnInfo {
            width: 100%;
            height: 272px;
        }
        .repPlantLists {
            overflow-y: auto;
        }

        .vux-header {
            .color-linear-gradient(@color-primary-light, @color-primary, 90deg);
            .vux-header-title {
                font-size: 20PX;
            }

            .vux-header-left {
                .left-arrow:before {
                    border: solid 1px @color-white;
                    border-width: 2px 0 0 2px;
                }
            }
        }
        .calculatorresult-blank {
            height: 150px;
            text-align: center;
            .flexLayout(center, center, column);
            .color-linear-gradient(@color-primary-light, @color-primary, 90deg);
            p {
                color: @color-white;

                &:first-child {
                    font-size: @font-size-small;
                }
                &:last-child {
                    font-size: 30Px;
                    font-weight: bold;
                }
            }
        }
        .calculatorresult-center {
            font-size: @font-size-small;
            color: @color-white;
            padding: 10px 0;
            height: 24px;
            .color-linear-gradient(@color-gradient-lightBlue-left, @color-primary, 45deg);
            text-align: center;
            .vux-flexbox-item {
                p {
                    span {
                        &:first-child {
                            display: inline-block;
                            margin-left: 3px;
                            font-size: @font-size-medium;
                        }
                        &:first-child {
                            display: inline-block;
                            margin-left: 3px;
                            font-size: @font-size-small;
                        }

                    }
                }
            }
        }
        .calculatorresult-body {
            padding: 0 12px;
            height: 32px;
            background-color: @color-background-default;
            color: @color-text-third;
            font-size: @font-size-medium;
            .flexLayout(center, center, row);
            text-align: center;

            span {
                display: block;
                flex: 1;
            }

        }
        .calculatorresult-detail {
            margin: 0 12px;
            height: 44px;
            .flexLayout(center, center, row);
            font-size: @font-size-medium;
            text-align: center;
            span {
                display: block;
                flex: 1;
            }
        }
    }
</style>

